# coding:utf-8
import uiautomator2 as u2
import time
import os
import datetime
import zipfile
import configparser
from word_excel_operation.labels_img_excel import AboutExcel
from word_excel_operation.word_excel_character import WriteWordToExcel
from word_excel_operation.get_word_tablet_img import GetImg
import re
import logging

def errorlog(func):
    logger = logging.getLogger()

    def wrapper(self, *args, **kwargs):
        try:
            return func(self, *args, **kwargs)  # 执行传入的fn参数
        except Exception as e:
            logger.error(msg=e, exc_info=True)

    return wrapper

class img():

    def __init__(self):
        """
        :param current_path 当前，目录的绝对路径
        """
        print('---------------------正在连接设备---------------------\n')
        self.d = u2.connect()
        path = os.popen("chdir").read()
        self.current_path = path.strip() #打印的地址末尾有个\n ， 这里把他去掉

    def makeFiles(self):

        nowTime = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
        #在excel_result文件夹下创建当前时间运行的文件夹作为当前运行的结果保存路径
        self.read_new_file = os.popen(r"cd excel_result && mkdir {} && cd {} && chdir".format(nowTime,nowTime)).read()
        self.make_result_file = self.read_new_file.strip()
        # logging.debug("本次运行结果的存储路径为：",self.make_result_file)
        print("本次运行结果的存储路径为：",self.make_result_file)
        return self.make_result_file

    def savelog(self):
        # print("---------------记录log--------------------")
        path = "{}\\main.log".format(self.make_result_file)
        logging.basicConfig(level=logging.DEBUG,  # 控制台打印的日志级别
                            filename=path,
                            filemode='w',  ##模式，有w和a，w就是写模式，每次都会重新写日志，覆盖之前的日志
                            # a是追加模式，默认如果不写的话，就是追加模式
                            format=
                            '%(asctime)s - [line:%(lineno)d] - %(levelname)s: %(message)s'
                            # '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
                            # 日志格式

                            )



    def readConfig(self):
        self.cf = configparser.ConfigParser()
        self.cf.read("./setting/config.ini",encoding="utf-8-sig")  # 读取配置文件

    def getScreenShot(self):
        nowTime = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
        self.picturePath = "./imgFiles/{}.jpg".format('nowTime')
        self.d.screenshot(self.picturePath)
        return self.picturePath

    def getTabletImgName(self):
        self.readConfig()
        table_img_name = self.cf.get("M11_ROW_WIFI",'table_img_name')
        # print(table_img_name)
        return table_img_name

    def getExcelName(self):
        self.readConfig()
        excel_name = self.cf.get("Excel_Name","excel_name")
        # print(excel_name)
        return excel_name


    @errorlog
    def enterLabels(self):
        self.savelog()
        # self.d = u2.connect()
        self.d.press('home')
        time.sleep(3)
        self.d.implicitly_wait(20)
        try:
            self.d.app_stop("com.android.settings")
        except:
            pass

        # 启动应用
        self.d.app_start("com.android.settings")
        print('\n---------------------应用启动成功---------------------\n')
        logging.debug("'---------------------应用启动成功---------------------'")
        self.sizeTuple = self.d.window_size()
        # 创建session连接对象，建议与设置应用的绑定连接
        s = self.d.session('com.android.settings', attach=True)
        time.sleep(3)
        # 获取设备的尺寸
        # print(self.d.window_size())

        x = self.sizeTuple[0]
        y = self.sizeTuple[1]
        # print("屏幕的宽为："+str(x) +",屏幕的高为："+str(y)) #获取屏幕的宽高
        # 1.进入设置之后，划动屏幕找到System
        time.sleep(3)
        # print("---------------------开始滑屏--------------------")
        self.d.swipe(x / 5 * 4, y / 5 * 4, x / 5 * 4, y / 5 * 1, 1, 50)
        self.d.swipe(x / 5 * 4, y / 5 * 4, x / 5 * 4, y / 5 * 1, 1, 50)
        # print("---------------------滑屏结束-----------------------")
        self.d.implicitly_wait(5)
        # 2.通过class和下标点击系统（开发者模式）
        n1 = self.d(className='android.widget.RelativeLayout').count
        self.d(className='android.widget.RelativeLayout')[n1 - 1].click()

        self.d(resourceId = "android:id/title",text = "Regulatory labels").click()
        logging.debug("----------点击监管标签成功-------------")

        #########################################################
        #读取所有得text，打印
        # count = self.d(className = "android.widget.ScrollView").count
        # count = self.d(className = "android.widget.ScrollView").child(className ="android.widget.RelativeLayout").child(className ="android.widget.LinearLayout").count


        list = []
        count = self.d(className ="android.widget.TextView").count

        # print("第一次一共有：",count,"个text元素")
        temp_list = []
        for  i  in range(count):

            element = self.d(className ="android.widget.TextView")[i].get_text(20)
            element = element.replace(" ","")
            if element.startswith('Thisdevice') or element.startswith('(1)thisdevice') \
                or element.startswith('and(2)this') :
                temp_list.append(element)

            str_temp_list = ''.join(temp_list)


            list.append(element.strip())
            # print(list)

        self.d.swipe(x / 5 * 4, y / 5 * 4, x / 5 * 4, y / 5 * 1, 1, 50)
        self.d.swipe(x / 5 * 4, y / 5 * 4, x / 5 * 4, y / 5 * 1, 1, 50)


        # print("#####################################################")

        count = self.d(className="android.widget.TextView").count
        # print("第二次一共有：", count, "个text元素")

        for i in range(count):
            element = self.d(className="android.widget.TextView")[i].get_text(20)
            element = element.replace(" ", "")
            if element in list:
                pass
            else:
                # print(element)
                list.append(element.strip())
        logging.debug("####################排查thiedevices#################################")


        try:
            for i in list:
                if i.startswith('Thisdevice'):
                    index = list.index(i)
                    list[index] = str_temp_list
                    a = list.pop(index+1)
                    b = list.pop(index+1)
                    logging.debug(str(a))
                    logging.debug(str(b))
        except:
            pass

        print("正在对比labels页面字符........\n")
        logging.debug("正在对比labels页面字符........")
        # print(list) #打印获取的平板的内容

        del list[0]  ##删除平板的第一行Regulatory labels（这个是平板上的左上角标题）
        list.remove('D200198201')
        list.remove('201-200851')


        table_msg = '\n'.join(list)  #把列表转化成字符串拼接起来



        # run = WriteWordToExcel("D:\Y_Script\\regulatory_labels\wordfiles\\1_E-label Guide for Lenovo TB-J606F for ROW.docx","./excel_result/excel_xlsx.xlsx","labels_msg")
        self.word_docx_path = self.current_path + '\wordfiles\\'+ self.getExcelName()
        logging.debug("word转换好的表格路径为：{}".format(self.word_docx_path))
        # run = WriteWordToExcel(excel_path,"./excel_result/excel_xlsx.xlsx","labels_msg")
        labels_compare_result_path = self.make_result_file + '\\labels_msg_compare.xlsx'
        run = WriteWordToExcel(self.word_docx_path,labels_compare_result_path,"labels_msg")
        #把平板上的监管信息写入到表格
        run.tablet_msg_write_excel(table_msg)


        # print(table_msg)

        # #获取当前页面的截图
        # self.getScreenShot()
        time.sleep(5)
        self.d.press("home")
        word_text_list = run.read_word()   #word中的每一行在一个列表中

        word_msg = '\n'.join(word_text_list)   #把word列表转化成字符串才能写进去表格




        if table_msg == word_msg:
            run.wirte_result("一样")
            print("字符对比结果：一样\n")
            logging.debug("字符对比结果：一样")

        else:
            if len(list) == len(word_text_list):
                differ_list = []
                for i in range(len(list)):
                    if list[i] != word_text_list[i]:
                        differ_list.append(word_text_list[i])
            elif len(list) > len(word_text_list):
                differ_list = []
                for i in range(len(word_text_list)):
                    if list[i] != word_text_list[i]:
                        differ_list.append(word_text_list[i])
            else :
                differ_list = []
                for i in range(len(list)):
                    if list[i] != word_text_list[i]:
                        differ_list.append(word_text_list[i])
            logging.debug("不一样的内容为:{}".format(differ_list))

            msg = '\n'.join(differ_list)
            run.wirte_result("不一样")
            print("字符对比结果：不一样\n")
            logging.debug("字符对比结果：不一样")
            run.wirte_backup(msg)



        self.d.app_stop("com.android.settings")
        print("平板监管标签的文字信息对比完毕！\n")
        logging.debug("平板监管标签的文字信息对比完毕！\n")
        print("-----------------------------------------\n")
        self.savelog()
        # #获取部分图片
        # self.getPartImg()
        #########################################################################

    @errorlog
    def get_tablet_img(self):
        self.savelog()
        '''
         APK提取器的包名为：com.zhanhong.apkextractor
         搜索框ID为 ： com.zhanhong.apkextractor:id/editTextSearch
         搜索按钮ID为 ： com.zhanhong.apkextractor:id/search

         需要输入的搜索名称为 ：Settings(系统)
        '''
        # self.d = u2.connect()

        print("开始进行labels图片对比！\n")
        logging.debug("开始提取apk解压，提取平板图片！")

        #每次运行这段代码前，需要把对应要用的文件夹全部清空
        logging.debug("正在清空文件夹！")
        os.popen("del /s/q .\\tablet_img\\* ")  # 清空tablet_img中的所有图片
        os.popen("del /s/q .\\word_img\\* ")  # 清空word_img中的所有图片
        # logging.debug("删除seeting文件")
        # os.popen("del /s/q .\\setting_apk_files\\*.* ")  # 要用删除文件夹的rdir操作

        time.sleep(15)

        #进入提取器中进行提取apk
        logging.debug("准备提取apk文件")

        try:
            self.d.app_stop("com.zhanhong.apkextractor")
        except:
            pass

        try:
            self.d.app_start("com.zhanhong.apkextractor")
            # # 创建session连接对象，建议与设置应用的绑定连接
            # self.d.session("com.zhanhong.apkextractor", attach=True)
        except:
            print("请检查设备是否安装apkextractor.apk")
            logging.debug("请检查设备是否安装apkextractor.apk")
            input("请输入回车键关闭本窗口，安装完成后重新启动~")

        time.sleep(3)

        try:
            #点击授权
            self.d(resourceId = "com.android.permissioncontroller:id/continue_button").click()
        except:
            pass

        try:
            self.d(resourceId="android:id/button1").click()
            # self.d(className = "android.widget.Button",text = '确定' or "ok").click()
        except:
            pass


        # self.d(resourceId = "com.zhanhong.apkextractor:id/editTextSearch").click()
        self.d(resourceId = "com.zhanhong.apkextractor:id/editTextSearch").send_keys("Settings")
        time.sleep(3)
        self.d(resourceId = "com.zhanhong.apkextractor:id/search").click()
        time.sleep(3)
        self.d(text = "com.android.settings").click()
        time.sleep(10) #等待提取apk
        try:
            #把已经提取到设备中的apk文件拉取到电脑文件里面
            os.popen("adb pull /sdcard/APK提取器 ./setting_apk_files")
        except:
            print("提取APK失败\n")

        time.sleep(10) #等待pull完apk
        self.d.app_stop("com.zhanhong.apkextractor") #提取完apk之后退出应用
        file_path = "./setting_apk_files/"
        apk_file_name = os.listdir(file_path)
        # print(apk_file_name)

        #


        for i in apk_file_name:
            if  re.match('^Settings.*apk', i) != None:
                logging.debug("内容：{},下标：{}".format(i,apk_file_name.index(i)))
                apk_file_path = file_path + i
                nowTime = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
                unzip_file_name = "settings_" + nowTime
                unzip_file_path = file_path +  unzip_file_name
                zip_apk_path = unzip_file_path + ".zip"

                os.rename(apk_file_path, zip_apk_path)
                logging.debug("重命名完毕")
                #获取需要提取得tablet_labels_img_name
                tablet_img_name = AboutExcel(None,None).getTabletImgName()
                zip_file = zipfile.ZipFile(zip_apk_path)
                print("已提取apk,正在解压,请稍等.......\n")
                logging.debug("已提取apk,正在解压,请稍等.......")
                #time.sleep(200)

                zip_file.extractall(unzip_file_path + "\\")  #如果不传path，默认为解压到当前目录

                zip_file.close()  # 关闭文件，必须有，释放内存
                time.sleep(10)
                logging.debug('................正在拷贝图片到电脑...............................')
                print('................正在拷贝图片到电脑...............................\n')
                for i in tablet_img_name:
                    #dos命令中文件夹为反斜杠 ”\“
                    os.popen("copy .\\setting_apk_files\\{}\\res\\drawable-hdpi-v4\\{}  .\\tablet_img\\  /Y".format(unzip_file_name,i))

        # 把解压之后文件中的图片提取出来 之后，把setting_apk_files中的文件全部删除
        time.sleep(10)
        # print("删除seeting文件")


        print("平板标签图片获取完成！\n")
        logging.debug("平板标签图片获取完成！")

    @errorlog
    def get_word_img(self):
        self.savelog()
        #获取word中的img
        word_docx_path = './wordfiles/' + self.getExcelName()
        GetImg().get_word_pictures(word_docx_path,'./word_img')


    @errorlog
    def compareImg(self):
        self.savelog()

        self.get_tablet_img()
        self.get_word_img()

        #执行把图片写入表格，并进行图片对比，结果写入表格
        #import的哪个py文件中的所有相对路径，都以本py文件作为原点路径进行获取相对路径
        #本方法中import的py文件中 ../ 路径 需改为  ./ 路径
        print("所有图片正在写入表格\n")
        logging.debug("所有图片正在写入表格")
        aa = AboutExcel('./tablet_img/','./word_img/')
        # print("保存路径为：",self.make_result_file)
        logging.debug("保存路径为：{}".format(self.make_result_file))
        aa.creat_img_excel(self.make_result_file)



if __name__ == '__main__':
    Run = img()
    Run.makeFiles()   #创建文件夹，先运行
    Run.enterLabels()   #对比字符程序
    Run.compareImg()   #对比图片
    print()
    input("请点击回车按键关闭当前窗口:")



